package orxatas.travelme.activity;

import java.io.File;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;

import orxatas.travelme.R;
import orxatas.travelme.databases.exceptions.PhotoNoInLocal;
import orxatas.travelme.databases.exceptions.UserNotInLocal;
import orxatas.travelme.entity.Entry;
import orxatas.travelme.entity.Photo;
import orxatas.travelme.entity.User;
import orxatas.travelme.manager.AccountManager;
import orxatas.travelme.manager.DataManager;
import orxatas.travelme.manager.EntryManager;
import orxatas.travelme.manager.PhotoManager;
import orxatas.travelme.manager.UserManager;
import orxatas.travelme.manager.exceptions.CantLoadPhotoFromFile;
import orxatas.travelme.sync.AsyncNoticeCode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.markupartist.android.widget.ActionBar;

public class EntryDetailsActivity extends Activity implements AsyncActivity{

	private final static String TAG = "travelme_EntryDetailsActivity";
	private int entryID;
	private User user;
	private int userID;
	private Entry entry;
	private UserManager userManager;
	private EntryManager entryManager;
	private PhotoManager photoManager;
	private AccountManager accountManager;
	private DateFormat formatter;
	private ProgressDialog dialog;
	private Date tmpDate;
	private ArrayList<Photo> photoList;
	private LinearLayout photosLayout;
	private TextView textViewAutor;
	private TextView textViewDate;
	private TextView textViewDate2Text;
	private TextView textViewDate2;
	private TextView textViewMainText;
	private TextView textViewOptionalText;
	private ImageView icon;
	private Button button;
	private Gallery gallery;
	private ImageAdapter adapter;
	private DataManager dataManager;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.entry_details);
	    
//	    formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	    //formatter = new SimpleDateFormat("yyyy-MM-dd");
	    formatter = DateFormat.getDateInstance();
	    tmpDate = new Date();
	    
	    ActionBar ab = (ActionBar) findViewById(R.id.actionbar);
		ab.setTitle(R.string.entry_details_title);
		
	    entryID = getIntent().getIntExtra("entry_id", -1);
	    
		accountManager = new AccountManager(this);
	    
		if(!accountManager.isLogged()){
			startActivity(new Intent(EntryDetailsActivity.this, LoginActivity.class));
			finish();
		}
		
		userManager = new UserManager(this);
		entryManager = new EntryManager(this);
		photoManager = new PhotoManager(this);
		dataManager = new DataManager(this);
		
	    user = accountManager.getUserLogged();
	    
	    
	    if(user != null) {
	    	userID = user.getId();
	    }
	    else{
	    	Log.e(TAG, "onCreate - no user logged");
	    	userID = -1;
	    }

	    if(entryID == -1) {
	    	finish();
	    }
	    
	    entry = entryManager.getEntry(entryID);
	    
	    photosLayout = (LinearLayout) findViewById(R.id.entry_details_photos);
		textViewAutor = (TextView) findViewById(R.id.entry_details_autor);
		textViewDate = (TextView) findViewById(R.id.entry_details_date);
		textViewDate2Text = (TextView) findViewById(R.id.entry_details_date2_text);
		textViewDate2 = (TextView) findViewById(R.id.entry_details_date2);
		textViewMainText = (TextView) findViewById(R.id.entry_details_text);
		textViewOptionalText = (TextView) findViewById(R.id.entry_details_text_optional);
		icon = (ImageView) findViewById(R.id.entry_details_feeling_icon);
		button = (Button) findViewById(R.id.entry_details_geopoint_button);
		gallery = (Gallery) findViewById(R.id.entry_details_gallery);

	    setContent();
	    
	}

	public void showProgressDialog(){
		if(dialog == null){
			dialog = ProgressDialog.show(EntryDetailsActivity.this, "", 
					getResources().getString(R.string.entry_details_progressdialog_text),true, false);
		}
		

	}
	
	public void hideProgressDialog(){
		if(dialog != null){
			dialog.dismiss();
			dialog = null;
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) { 
	  MenuInflater inflater = getMenuInflater(); 
	  inflater.inflate(R.layout.menu_entry_details, menu); 
	  return true; 
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch(item.getItemId()){
		case R.id.menu_entry_details_disconnect:
			accountManager.disconnect();
			startActivity(new Intent(EntryDetailsActivity.this, LoginActivity.class));
			finish();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private void setContent(){
		setAutor();
		setDate();
		setSecondDate();
		setText();
		setOptionalText();
		setFeelingIcon();
		setGeopoint();
		setPhotos();
	}
	
	private void reloadContent(){
		setAutor();
		setDate();
		setSecondDate();
		setText();
		setOptionalText();
		setFeelingIcon();
		setGeopoint();
		reloadPhotos();
	}
	
	
	
	private void setAutor(){
		String autor = "";
		if(entry.getIdAutor() == userID){
    		autor = user.getUserName();
    		if(autor == null || autor ==""){
    			autor = user.getEmail();
    			Log.i(TAG, "user mail");
    		}
    	}
    	else{
    		try {
				User u = userManager.getUser(entry.getIdAutor());
				autor = u.getUserName();
        		if(autor == null || autor ==""){
        			autor = u.getEmail();
        		}
			} catch (UserNotInLocal e) {
				autor = String.valueOf(entry.getIdAutor());
			} catch (Exception e){
				autor = String.valueOf(entry.getIdAutor());
			}
    	}
		
		textViewAutor.setText(autor);
		
	}
	private void setDate(){
		long date = ((long) entry.getDate())*1000;
		tmpDate.setTime(date);
		textViewDate.setText(formatter.format(tmpDate));
	}
	
	private void setSecondDate(){
		
		if(entry.getCreation() != entry.getDate()){
			tmpDate.setTime(((long) entry.getDate())*1000);
			textViewDate2.setText(formatter.format(tmpDate));
			textViewDate2Text.setVisibility(View.VISIBLE);
			textViewDate2.setVisibility(View.VISIBLE);
		}
		else{
			textViewDate2Text.setVisibility(View.GONE);
			textViewDate2.setVisibility(View.GONE);
		}

	}
	
	private void setText(){
		
		/*if(!(entry.getText() == null) && !(entry.getText() == "")){			
			
			textViewMainText.setText(entry.getText());
			textViewMainText.setVisibility(View.VISIBLE);
		}
		else{
			textViewMainText.setVisibility(View.GONE);
		}*/
	}
	
	private void setOptionalText(){
		
		if(!(entry.getOpcionalText() == null) && !(entry.getText() == "")){			
			
			textViewOptionalText.setText(entry.getOpcionalText());
			textViewOptionalText.setVisibility(View.VISIBLE);
		}
		else{
			textViewOptionalText.setVisibility(View.GONE);
		}
	}
	
	private void setFeelingIcon(){
		switch(entry.getFeeling()){
			case 0:{
				icon.setImageResource(R.drawable.ic_entry_feeling_sad);
				break;
			}
			case 1:{
				icon.setImageResource(R.drawable.ic_entry_feeling_normal);
				break;
			}
			case 2:{
				icon.setImageResource(R.drawable.ic_entry_feeling_happy);
				break;
			}
			default:{
				icon.setImageResource(R.drawable.ic_entry_feeling_normal);
				break;
			}
		}
			
	}
	
	private void setGeopoint(){
		
		
		button.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				
				Intent i = new Intent(EntryDetailsActivity.this, MapPlacesActivity.class);
				i.putExtra("id_group", entry.getIdGroup());     
				i.putExtra("id_place", entry.getIdPlace());
				startActivity(i);
				
			}
		});
	}
	
	private void loadPhotoList(){
		photoList = new ArrayList<Photo>();
	    Photo p;
		for(Integer i: entry.getPhotos()){
			try {
				p = photoManager.getPhoto(i);
				if(p != null && p.getLocalPath() != null && p.getLocalPath() != ""){
					photoList.add(p);
				}
			} catch (PhotoNoInLocal e) {
			}
			
		}
	}
	
	private void setPhotos(){
		if(!(entry.getPhotos() == null) && !(entry.getPhotos().size() == 0)){

		    loadPhotoList();
			if(photoList.size() > 0){
				photosLayout.setVisibility(View.VISIBLE);
				
				adapter = new ImageAdapter(this,R.layout.gallery_element,photoList);
			    gallery.setAdapter(adapter);
			    gallery.setOnItemClickListener(new OnItemClickListener() {
			        public void onItemClick(AdapterView parent, View v, int position, long id) {
			            
			            Intent intent = new Intent();
			            intent.setAction(android.content.Intent.ACTION_VIEW);
			            intent.setDataAndType(Uri.fromFile(new File(adapter.getItem(position).getLocalPath())), "image/*");
			            startActivity(intent);
			        }
			    });
			}
			else{
				photosLayout.setVisibility(View.GONE);
			}
			
		}
		else{
			photosLayout.setVisibility(View.GONE);
		}
		
	}
	
	private void reloadPhotos(){
		if(!(entry.getPhotos() == null) && !(entry.getPhotos().size() == 0)){
			loadPhotoList();
			if(photoList.size() > 0){
				photosLayout.setVisibility(View.VISIBLE);
				adapter.setNotifyOnChange(false);
				adapter.clear();
				for(Photo p: photoList){
					adapter.add(p);
				}
				adapter.notifyDataSetChanged();
			}
			else{
				photosLayout.setVisibility(View.GONE);
			}
		}
		else{
			photosLayout.setVisibility(View.GONE);
		}
	}
	
	@Override
	public void asyncNotice(AsyncNoticeCode code) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Activity getActivity() {
		return this;
	}

	@Override
	public void syncStarted() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void syncEnded() {
		// TODO Auto-generated method stub
		
	}
	
	
	private class ImageAdapter extends ArrayAdapter<Photo> {
		private int mGalleryItemBackground;
        private ArrayList<Photo> items;
        private Photo photo;
        private LayoutInflater inflater;

        public ImageAdapter(Context context, int textViewResourceId, ArrayList<Photo> items) {
                super(context, textViewResourceId, items);
                TypedArray attr = context.obtainStyledAttributes(R.styleable.Gallery1);
                mGalleryItemBackground = attr.getResourceId(
                        R.styleable.Gallery1_android_galleryItemBackground, 0);
                attr.recycle();
                this.items = items;
                inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder holder;
                if (convertView == null) {
                	
                    convertView = inflater.inflate(R.layout.gallery_element, null);
                    
                    holder = new ViewHolder();
                    holder.image = (ImageView) convertView.findViewById(R.id.gallery_image);
            		
            		convertView.setTag(holder);
                }
                else  
    	        {  
    	            holder = (ViewHolder) convertView.getTag();  
    	        } 
                photo = items.get(position);
                if (photo != null) {
                	try {
						holder.image.setImageBitmap(photoManager.path2Bitmap(photo.getLocalPath()));
					} catch (CantLoadPhotoFromFile e) {
					}
            		holder.image.setBackgroundResource(mGalleryItemBackground);
                        
                }
                
                return convertView;
        }
}
	
	
	
	static class ViewHolder  
    {  
        public ImageView image;   
    }



	@Override
	public void syncAndWaitCallStarted() {
		showProgressDialog();
		
	}


	@Override
	public void syncAndWaitCallEnded(Object o, int syncAction) {
		hideProgressDialog();
		
	}

}
